package org.qiandaosystem.qiandaosystemsource.controller;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import lombok.Data;
import lombok.RequiredArgsConstructor;
import org.qiandaosystem.qiandaosystemsource.common.ApiResponse;
import org.qiandaosystem.qiandaosystemsource.service.TeacherService;
import org.qiandaosystem.qiandaosystemsource.service.QrCodeSignService;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import io.swagger.v3.oas.annotations.media.Schema;

import java.io.ByteArrayOutputStream;
import java.time.LocalDateTime;
import java.util.List;

@RestController
@RequestMapping("/api/teacher")
@RequiredArgsConstructor
@SecurityRequirement(name = "bearerAuth")
public class TeacherController {
    
    private final TeacherService teacherService;
    private final QrCodeSignService qrCodeSignService;

    @Data
    public static class CreateSignActivityRequest {
        @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
        private LocalDateTime startTime;
        
        @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
        private LocalDateTime endTime;
    }

    @Data
    public static class CreateCodeSignActivityRequest {
        @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
        private LocalDateTime startTime;
        
        @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
        private LocalDateTime endTime;

        @Schema(description = "4位数签到码", example = "1234")
        public String signCode;
    }

    @Operation(summary = "创建普通签到")
    @PostMapping("/sign-activities/normal")
    public ApiResponse<?> createNormalSignActivity(
            @RequestBody CreateSignActivityRequest request,
            @RequestHeader("Authorization") String token) {
        String jwt = token.substring(7);
        return teacherService.createNormalSignActivity(jwt, request.getStartTime(), request.getEndTime());
    }

    @Operation(summary = "修改普通签到")
    @PutMapping("/sign-activities/{id}")
    public ApiResponse<?> updateSignActivity(
            @PathVariable Integer id,
            @RequestBody CreateSignActivityRequest request,
            @RequestHeader("Authorization") String token) {
        String jwt = token.substring(7);
        return teacherService.updateSignActivity(jwt, id, request.getStartTime(), request.getEndTime());
    }

    @Operation(summary = "删除普通签到")
    @DeleteMapping("/sign-activities/{id}")
    public ApiResponse<?> deleteSignActivity(
            @PathVariable Integer id,
            @RequestHeader("Authorization") String token) {
        String jwt = token.substring(7);
        return teacherService.deleteSignActivity(jwt, id);
    }

    @Operation(summary = "查看所有签到活动")
    @GetMapping("/sign-activities")
    public ApiResponse<?> getAllSignActivities(
            @RequestHeader("Authorization") String token) {
        String jwt = token.substring(7);
        return teacherService.getAllSignActivities(jwt);
    }

    @Operation(summary = "创建签到码签到")
    @PostMapping("/sign-activities/code")
    public ApiResponse<?> createCodeSignActivity(
            @RequestBody CreateCodeSignActivityRequest request,
            @RequestHeader("Authorization") String token) {
        if (!request.getSignCode().matches("\\d{4}")) {
            return ApiResponse.error("签到码必须是4位数字");
        }
        String jwt = token.substring(7);
        return teacherService.createCodeSignActivity(jwt, request.getStartTime(), 
                request.getEndTime(), request.getSignCode());
    }


    @Operation(summary = "获取签到活动统计信息")
    @GetMapping("/sign-activities/statistics")
    public ApiResponse<?> getSignActivitiesStatistics(
            @RequestHeader("Authorization") String token) {
        String jwt = token.substring(7);
        return teacherService.getSignActivitiesStatistics(jwt);
    }

    @Operation(summary = "获取单个签到活动的统计信息")
    @GetMapping("/sign-activities/{id}/statistics")
    public ApiResponse<?> getSignActivityStatistics(
            @PathVariable Integer id,
            @RequestHeader("Authorization") String token) {
        String jwt = token.substring(7);
        return teacherService.getSignActivityStatistics(jwt, id);
    }

    @Operation(summary = "创建二维码签到")
    @PostMapping("/sign-activities/qrcode")
    public ApiResponse<?> createQrCodeSignActivity(
            @RequestBody CreateSignActivityRequest request,
            @RequestHeader("Authorization") String token) {
        String jwt = token.substring(7);
        return qrCodeSignService.createQrCodeSignActivity(jwt, request.getStartTime(), request.getEndTime());
    }

    @Operation(summary = "获取二维码")
    @GetMapping("/sign-activities/{id}/qrcode")
    public ApiResponse<?> getQrCode(
            @PathVariable Integer id,
            @RequestHeader("Authorization") String token) {
        String jwt = token.substring(7);
        return qrCodeSignService.getQrCode(jwt, id);
    }
    @Data
    public static class CreateGestureSignActivityRequest {
        @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
        private LocalDateTime startTime;

        @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
        private LocalDateTime endTime;

        @Schema(description = "九宫格手势的坐标点", example = "1,2,3,4")
        public String gesturePoint;
    }

    @Operation(summary = "创建九宫格手势签到")
    @PostMapping("/sign-activities/gesture")
    public ApiResponse<?> createGestureSignActivity(
            @RequestBody CreateGestureSignActivityRequest request,
            @RequestHeader("Authorization") String token) {
        // 手势校验逻辑（可以根据需要自定义，比如坐标点必须是1-9且不重复等）
        String[] points = request.getGesturePoint().split(",");
        if (points.length != 4) {
            return ApiResponse.error("手势坐标点必须为4个");
        }

        String jwt = token.substring(7);
        return teacherService.createGestureSignActivity(jwt, request.getStartTime(),
                request.getEndTime(), request.getGesturePoint());
    }
    @Data
    public static class CreateLocationSignActivityRequest {
        @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
        private LocalDateTime startTime;

        @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
        private LocalDateTime endTime;

        @Schema(description = "地理位置经度", example = "116.397428")
        private Double longitude;

        @Schema(description = "地理位置纬度", example = "39.90923")
        private Double latitude;

        @Schema(description = "允许的误差范围（米）", example = "50")
        private Integer radius;
    }
    @Operation(summary = "创建位置签到")
    @PostMapping("/sign-activities/location")
    public ApiResponse<?> createLocationSignActivity(
            @RequestBody CreateLocationSignActivityRequest request,
            @RequestHeader("Authorization") String token) {
        String jwt = token.substring(7);
        return teacherService.createLocationSignActivity(jwt, request.getStartTime(), request.getEndTime(),
                request.getLongitude(), request.getLatitude(), request.getRadius());
    }

} 